package com.hydra.cron.server.cron.listener;

import com.hydra.cron.common.constants.C;
import com.hydra.cron.common.curator.helper.CuratorHelper;
import com.hydra.cron.common.utils.ObjectUtil;
import com.hydra.cron.common.utils.PathUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Random;

/**
 * hdyraCron Created by ZhengGong on 15/12/28.
 * PackageName com.hydra.cron.server.cron.listener
 * Description
 */
public class SupportChildNodeListener extends AbstractChildNodeListener {
    private static final Logger LOG = LoggerFactory.getLogger(SupportChildNodeListener.class);

    private final String parentPath;

    public SupportChildNodeListener(String parentPath) {
        this.parentPath = parentPath;
    }

    @Override
    public void add(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {

    }

    @Override
    public void removed(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
        LOG.info(pathChildrenCacheEvent.getData().getPath());
        List<String> list = CuratorHelper.getChildrenNodePath(parentPath);
        if (ObjectUtil.isNotEmpty(list)) {
            boolean isRun = false;
            for (String token : list) {
                if (C.JOB_STATUS.RUN.equals(CuratorHelper.getInstance().getData(PathUtil.path(parentPath, token)))) {
                    isRun = true;
                }
            }

            if (isRun) {
                return ;
            }

            CuratorHelper.getInstance().update(PathUtil.path(parentPath, list.get(new Random().nextInt(list.size()))), C.JOB_STATUS.RUN);
        }
    }

    @Override
    public void update(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
        LOG.info(pathChildrenCacheEvent.getData().getPath() + "   " + new String(pathChildrenCacheEvent.getData().getData()));
    }
}
